package com.yonyou.pmclouds.basecom.util;

import com.yonyou.pmclouds.basecom.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

@Slf4j
public class DateUtils {

    public static String INIT_DATE_STRING = "1970-01-01 00:00:00";

    public static Date asDateBegin(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        calendar.set(Calendar.AM_PM, 0);   //上午
        return calendar.getTime();
    }

    public static Date asDateEnd(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR, 11);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 0);

        calendar.set(Calendar.AM_PM, 1);   //下午
        return calendar.getTime();
    }

    public static Date calculateDate(Date date, int day) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, day);
        return calendar.getTime();
    }

    public static long getDaysBetween(Date start, Date end) {
        start = asDateBegin(start);
        end = asDateEnd(end);
        long days = end.getTime() - start.getTime() + 1000;
        days = days / (24 * 60 * 60 * 1000);
        return days;
    }

    public static Date formatDate(Date date) throws BusinessException {
        if(date == null){
            return null;
        }
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String dateStr = simpleDateFormat.format(date);
            return simpleDateFormat.parse(dateStr);
        } catch(ParseException e){
            log.error("时间转换失败：" + e);
            throw new BusinessException("时间转换失败：" + e.getMessage());
        }
    }

    public static Date transToDate(String datetime) throws BusinessException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

        try {
            Date date = simpleDateFormat.parse(datetime);
            return date;
        } catch (ParseException e) {
            log.error("时间转换异常");
            throw new BusinessException("时间转换失败:" +e.getMessage());
        }
    }

    public static String transToString(Date date){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String result = simpleDateFormat.format(date);
        return result;
    }
}
